﻿using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web.Mvc;
using AutoMapper;

using PagedList;
using SIG.Service;
using SIG.Basic.Helper;
using SIG.Model;
using SIG.Model.DTO;
using SIG.Model.ViewModel.Back;
using SIG.WebUI.Areas.Admin.Models;
using System;
using SIG.Model.Extensions;

namespace SIG.WebUI.Areas.Admin.Controllers
{
    [Authorize]
    //[InitializeSimpleMembership]
    public class ArticleController : AdminController
    {
        private readonly ICategoryService _categoryService;
        private readonly IArticleService _articleService;
        private readonly IPageMetaService _pageMetaService;


        public ArticleController(ICategoryService categoryService,IArticleService articleService, IPageMetaService pageMetaService)
        {
            _categoryService = categoryService;
            _articleService = articleService;
            _pageMetaService = pageMetaService;

            AjaxResult = new Model.ViewModel.AjaxResultVM();
        }
        #region 新闻
        

        //
        // GET: /Admin/News/


        [Authorize(Roles = "创始人,系统管理")]
        public ActionResult Index(int? page, int? categoryId)
        {

            var articleListVM = new ArticleListVM();

            articleListVM.CategoryId = categoryId??0;
            articleListVM.PageIndex = (page ?? 1) - 1;
            articleListVM.PageSize = Site.Settings.Article.PageSize;

            var articles = _articleService.SearchArticles(articleListVM.PageIndex, articleListVM.PageSize, articleListVM.CategoryId);
            var articleDtos = Mapper.Map<IEnumerable<Article>, IEnumerable<ArticleDTO>>(articles.AsEnumerable());

          
            articleListVM.Articles = articleDtos;
            articleListVM.TotalCount = _articleService.SearchArticlesCount(articleListVM.CategoryId);
            articleListVM.Categories = GetCategoryList(articleListVM.CategoryId);

            var articlesAsIPagedList = new StaticPagedList<ArticleDTO>(articleListVM.Articles, articleListVM.PageIndex + 1, articleListVM.PageSize, articleListVM.TotalCount);
            ViewBag.OnePageOfArticles = articlesAsIPagedList;

            return View(articleListVM);
          
        }


       [Authorize(Roles = "创始人,系统管理")]
        public ActionResult Add()
        {

           var article = new ArticlePageMetaDTO { Active = true};

           var categorys = _categoryService.GetActiveCategories(ModelType.NEWS); 
            var lCategorys = new SelectList(categorys, "Id", "Title");
                         
            ViewBag.Categories = lCategorys;
            return View(article);
        }


        [HttpPost]
         [Authorize(Roles = "创始人,系统管理")]
        public JsonResult Add(ArticlePageMetaDTO article)
        {
            if (!ModelState.IsValid)
            {
                var message = string.Join(" | ", ModelState.Values.SelectMany(v => v.Errors)
                    .Select(e => e.ErrorMessage));

                AjaxResult.SetError(message);

                return Json(AjaxResult, JsonRequestBehavior.DenyGet);

            }

            try
            {

           
                var newArticle = Mapper.Map<ArticlePageMetaDTO, Article>(article);
                _articleService.Create(newArticle);         
          
                if (!string.IsNullOrEmpty(article.Keywords) || !string.IsNullOrEmpty(article.SEODescription))
                {
                    var pageMeta = new PageMeta()
                    {
                        ObjectId = newArticle.Id,
                        Keyword = article.Keywords,
                        Description = article.SEODescription,
                        ModelType = ModelType.NEWS
                    };
                    _pageMetaService.Create(pageMeta);
                }

                AjaxResult.Message = String.Format(Site.AlertCreateSuccess, Site.Settings.Article.SetName);
                return Json(AjaxResult, JsonRequestBehavior.DenyGet);

            }catch (Exception er)
            {
                AjaxResult.SetError(er.Message);

                return Json(AjaxResult, JsonRequestBehavior.DenyGet);
            }


        }

        [Authorize(Roles = "创始人,系统管理")]
        public ActionResult Edit(int Id)
        {
            var vArticle = _articleService.GetById(Id);

            if (vArticle != null)
            {
                var editArticle = Mapper.Map<Article, ArticlePageMetaDTO>(vArticle);

                var pageMeta = _pageMetaService.GetPageMeta(ModelType.NEWS, editArticle.Id);
                if (pageMeta != null)
                {
                    editArticle.Keywords = pageMeta.Keyword;
                    editArticle.SEODescription = pageMeta.Description;
                }

                var categorys = _categoryService.GetActiveCategories(ModelType.NEWS);
                var lCategorys = new SelectList(categorys, "Id", "Title");

                ViewBag.Categories = lCategorys;
                return View(editArticle);
            }
            return View("NotFound");
        }

        [HttpPost]
        [ValidateInput(false)]
         [Authorize(Roles = "创始人,系统管理")]
                               
        public JsonResult Edit(ArticlePageMetaDTO article)
        {
            if (!ModelState.IsValid)
            {
                var message = string.Join(" | ", ModelState.Values.SelectMany(v => v.Errors)
                    .Select(e => e.ErrorMessage));

                AjaxResult.SetError(message);             

                return Json(AjaxResult, JsonRequestBehavior.DenyGet);

            }

            try
            {
                var editArticle = Mapper.Map<ArticlePageMetaDTO, Article>(article);

                _articleService.Update(editArticle);

                var pageMeta = _pageMetaService.GetPageMeta(ModelType.NEWS, editArticle.Id);
                pageMeta = pageMeta ?? new PageMeta();


                if (!string.IsNullOrEmpty(article.Keywords) || !string.IsNullOrEmpty(article.SEODescription))
                {

                    pageMeta.ObjectId = article.Id;
                    pageMeta.Keyword = article.Keywords;
                    pageMeta.Description = article.SEODescription;
                    pageMeta.ModelType = ModelType.PRODUCT;

                    if (pageMeta.Id > 0)
                    {
                        _pageMetaService.Update(pageMeta);
                    }
                    else
                    {
                        _pageMetaService.Create(pageMeta);
                    }
                }

                AjaxResult.Message = String.Format(Site.AlertUpdateSuccess, Site.Settings.Article.SetName);
                return Json(AjaxResult, JsonRequestBehavior.DenyGet);

            }
            catch (Exception er)
            {
                AjaxResult.SetError(er.Message);

                return Json(AjaxResult, JsonRequestBehavior.DenyGet);
            }

          
        }

        // DELETE: /User/DeleteSite
        [HttpDelete]
         [Authorize(Roles = "创始人,系统管理")]
        public JsonResult Delete(int id)
        {

            Article vArticle = _articleService.GetById(id);

            if (vArticle != null)
            {
                //string imgurl = Server.MapPath(vCategory.ImageURL);
                //if (System.IO.File.Exists(imgurl))
                //{
                //    System.IO.File.Delete(imgurl);    //删除缩略图
                //}

                _articleService.Delete(vArticle);
              
                return Json(true, JsonRequestBehavior.DenyGet);
            }

            return Json(false, JsonRequestBehavior.DenyGet);
        }

        #endregion


        #region 新闻分类

        public ActionResult Autocomplete(string term)
        {
            var model = _categoryService.GetActiveCategories(ModelType.NEWS)
                .Where(b => b.Title.StartsWith(term))
                .OrderByDescending(b => b.Importance).ThenByDescending(b => b.CreatedDate)
                .Take(10)
                .Select(b => new
                {
                    label = b.Title
                });

            return Json(model, JsonRequestBehavior.AllowGet);

        }

        
      

        public List<SelectListItem> GetCategoryList(int? categoryId)
        {
            var categorys = _categoryService.GetActiveCategories(ModelType.NEWS);
            List<SelectListItem> lCategorys = new List<SelectListItem>();
            foreach (var category in categorys)
            {
                var sli = new SelectListItem
                {
                    Text = category.Title,
                    Value = category.Id.ToString(),
                    Selected = (categoryId == category.Id)
                };

                lCategorys.Add(sli);

            }
            lCategorys.Insert(0, new SelectListItem { Text = "--按分类过滤--", Value = "" });

            return lCategorys;
        }
        #endregion
    }
}
